package org.ant.util;

import java.io.FileInputStream;

import org.ant.ctrl.CodeErrorManager;
import org.ant.ctrl.CodesManager;
import org.ant.handler.TACGenerator;
import org.ant.parser.ASTStart;
import org.ant.parser.Eg4;
import org.ant.parser.Eg4DumpVisitor;
import org.ant.parser.Eg4Visitor;
import org.ant.parser.Node;

/**
 * 
 * @author Eric Qian
 * 
 * this class will be destoried after Hom2
 */
public class Code {

	private String path;
	private ASTStart ast;
	private Node selNode;
	private Eg4 t;
	private boolean newFlag;
	private String output;

	public Code(String path) {
		super();
		this.path = path;

		init();
	}

	public Code(String path, ASTStart ast) {
		super();
		this.path = path;
		this.ast = ast;
		init();
	}

	private void init() {
		if (path != null) {
			try {
				CodeErrorManager.clear();
				boolean first = true;
				if (ast != null) {
					first = false;
				}
				t = new Eg4(new FileInputStream(path));
				ast = t.Start();
				Eg4Visitor v = new Eg4DumpVisitor();
				ast.jjtAccept(v, null);

				TACGenerator.getInstance().generateTAC(ast, t.getSTHandler());

				output = TACGenerator.getInstance().getOutput();
				
				CodeErrorManager.display();
				// System.out.println(output);

				t.printInfo();
				if (!first) {
					CodesManager.getInstane().broadCasting(
							CodesManager.INF_COMPILE);
				}
			} catch (Exception e) {
				System.out.println("Oops.");
				System.out.println(e.getMessage());
				output = null;
				e.printStackTrace();
			}
		} else {
			newFlag = true;
		}
	}

	public boolean compile() {
		if (path != null) {
			init();
			return true;
		}
		return false;
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public ASTStart getAst() {
		return ast;
	}

	public int getStatNum() {
		return t.getParserHandler().getStmtNum();
	}

	public int getWeight() {
		return t.getParserHandler().getWeight();
	}

	public Object[] getTypes() {
		return t.getSTHandler().getUsedTypeList().toArray();
	}

	public Object[] getDefineTypes() {
		return t.getSTHandler().getDefineTypeList().toArray();
	}

	public String getOutput() {
		return output;
	}

	public boolean isNew() {
		return newFlag;
	}

	public Node getSelNode() {
		return selNode;
	}

	public void setSelNode(Node selNode) {
		this.selNode = selNode;
		// System.out.println("!!!" + selNode.toString());
		TACGenerator.getInstance().generateTAC(selNode, t.getSTHandler());
		output = TACGenerator.getInstance().getOutput();
	}

}
